<template>
  <div class="p-2">
    <el-card>
      <div class="card-header">{{ form.name }}详细信息</div>
      <el-divider />
      <div class="row">
        <div class="col">
          <div class="label">创建时间：</div>
          <div class="value">{{ form.createTime||'' }}</div>
        </div>
        <div class="col">
          <div class="label">用工姓名：</div>
          <div class="value">{{ form.name||'' }}</div>
        </div>
        <div class="col">
          <div class="label">企业名称：</div>
          <div class="value">{{ '' }}</div>
        </div>
        <div class="col">
          <div class="label">身份证号：</div>
          <div class="value">{{ form.cardId||'' }}</div>
        </div>
        <div class="col">
          <div class="label">手机号：</div>
          <div class="value">{{ form.phone||'' }}</div>
        </div>
        <div class="col">
          <div class="label">邮箱：</div>
          <div class="value">{{ form.email||'' }}</div>
        </div>
        <div class="col">
          <div class="label">性别：</div>
          <div class="value">{{ form.sex||'' }}</div>
        </div>
        <div class="col">
          <div class="label">民族：</div>
          <div class="value">{{ form.nation||'' }}</div>
        </div>
        <div class="col">
          <div class="label">生日：</div>
          <div class="value">{{ form.birthday||'' }}</div>
        </div>
        <div class="col">
          <div class="label">有效期：</div>
          <div class="value">{{ form.expiryDate||'' }}</div>
        </div>
        <div class="col">
          <div class="label">地址：</div>
          <div class="value">{{ form.address||'' }}</div>
        </div>
        <div class="col">
          <div class="label">签发机关：</div>
          <div class="value">{{ form.issue||'' }}</div>
        </div>
        <div class="col">
          <div class="label">实名状态：</div>
          <div class="value">{{ form.isAuth == 1?'已实名':'未实名'||'' }}</div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <div class="label">身份证正面：</div>
          <div class="value">
            <ImagePreview :width="100" :height="100" :src="form.cardPositive" :preview-src-list="[form.cardPositive]" />
          </div>
        </div>
        <div class="col">
          <div class="label">身份证反面：</div>
          <div class="value">
            <ImagePreview :width="100" :height="100" :src="form.cardBack" :preview-src-list="[form.cardBack]" />
          </div>
        </div>
        <div class="col">
          <button class="el-button el-button--primary" v-if="!form.cardBack || !form.cardPositive" @click="handleCardUpload">上传身份证</button>
        </div>
      </div>
      <div class="card-header mt40">银行卡列表</div>
      <el-divider />
      <el-table :data="bankList" border>
        <!-- <el-table-column label="结算通道" align="center" min-width="160" prop="passage" /> -->

        <el-table-column label="银行名称" align="center" min-width="160" prop="bankType" />
        <el-table-column label="银行卡号" align="center" min-width="160" prop="bankCard" />
        <el-table-column label="预留手机号" align="center" min-width="160" prop="phoneNoHide" />
        <el-table-column label="操作" align="center" min-width="160">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="card-footer">
        <el-button @click="returnOn()">返回</el-button>
      </div>
    </el-card>
    <!-- 身份证证件修改 -->
    <el-dialog v-model="infoEditVisible" title="身份证证件修改" width="800px">
      <el-form ref="infoEditFormRef" :model="infoEditForm" :rules="rules" label-width="auto">
        <el-row :gutter="20">
          <template v-if="checkRole(5,7)">
            <el-col :span="12">
              <el-form-item label="身份证正面：" prop="cardPositive">
                <imageUpload v-if="infoEditForm.cardPositive" v-model="infoEditForm.cardPositive" modelKey="url" :limit="1" :isShowTip="false" />
                <template v-else description="请上传身份证正面照片">
                  <imageUpload v-model="infoEditForm.cardPositive" modelKey="url" :limit="1" :isShowTip="false" />
                </template>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="身份证反面：" prop="cardBack">
                <imageUpload v-if="infoEditForm.cardBack" v-model="infoEditForm.cardBack" modelKey="url" :limit="1" :isShowTip="false" />
                <template v-else description="请上传身份证反面照片">
                  <imageUpload v-model="infoEditForm.cardBack" modelKey="url" :limit="1" :isShowTip="false" />
                </template>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="infoEditVisible = false">关 闭</el-button>
          <el-button type="primary" :loading="subLoading" @click="infoEditSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 编辑弹框 -->
    <el-dialog v-model="dialogVisible" title="编辑银行卡信息" width="500px" append-to-body>
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="100px">
        <el-form-item label="结算通道" prop="passage">
          <el-select v-model="editForm.passage" placeholder="请选择结算通道">
            <el-option v-for="item in settleChannelList" :key="item.id" :label="item.channelName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="银行名称" prop="bankType">
          <el-input v-model="editForm.bankType" placeholder="请输入银行名称" />
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankCard">
          <el-input v-model="editForm.bankCard" placeholder="请输入银行卡号" />
        </el-form-item>
        <el-form-item label="预留手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入预留手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="memberDetail" lang="ts">
import api from '@/api/workMag/customerImport';
import { checkRole } from '@/utils/permission'; // 权限判断函数
import { getToken } from '@/utils/auth';
import { MemberInfoVo, MemberBankListVo,InfoEditVo} from '@/api/workMag/customerImport/types';
import { pa } from 'element-plus/es/locale';
import type { UploadProps } from "element-plus";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
//身份证件修改
const infoEditFormRef = ref<ElFormInstance>();
const infoEditVisible = ref(false);
const subLoading = ref(false);
const infoEditForm = ref<InfoEditVo>({
  id: '',
  cardPositive: '',
  cardBack: '',
  name: '',
});

const form = ref<MemberInfoVo>({
  addBy: '',
  address: '',
  addTime: '',
  alipayLogonId: '',
  bankAccId: '',
  bankCard: '',
  bankType: '',
  birthday: '',
  /**
   * 身份证反面
   */
  cardBack: '',
  /**
   * 身份证号
   */
  cardId: '',
  /**
   * 身份证正面
   */
  cardPositive: '',
  /**
   * 创建时间
   */
  createTime: '',
  editer: '',
  editTime: '',
  expiryDate: '',
  id: '',
  isAuth: '',
  isAuthentication: '',
  isRegister: '',
  isSign: '',
  issue: '',
  issueDate: '',
  moneyYear: '',
  moneyYearDate: '',
  /**
   * 用工姓名
   */
  name: '',
  nation: '',
  openId: '',
  /**
   * 手机号
   */
  phone: '',
  /**
   * 人脸照片
   */
  photoPath: '',
  referrerBy: '',
  sex: '',
  signTime: '',
  status: '',
  /**
   * 账户状态
   */
  statusStr: '',
  tag: '',
  userArea: '',
  userAreaName: ''
});
const bankList = ref<MemberBankListVo[]>([]);
const route = useRoute();
const memberId = ref<any>('');
const workId = ref('');
// 弹框显示状态
const dialogVisible = ref(false);
// 编辑表单对象
const editForm = ref({
  id: '',
  bankType: '',
  bankCard: '',
  phone: '',
  workId: '',
  passage: '' // 添加结算通道字段
});
// 表单校验规则
const rules = {
  bankType: [{ required: true, message: '请输入银行名称', trigger: 'blur' }],
  bankCard: [{ required: true, message: '请输入银行卡号', trigger: 'blur' }],
  passage: [{ required: true, message: '请选择结算通道', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入预留手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
};
//上传补充身份证
const handleCardUpload = async () => {
  infoEditVisible.value = true;
  // const res = await api.customerImporDetail(row.id);
  infoEditForm.value.id = form.value.id;
  infoEditForm.value.name = form.value.name;
  infoEditForm.value.cardPositive = form.value.cardPositive;
  infoEditForm.value.cardBack =form.value.cardBack;
  infoEditForm.value.cardId = form.value.cardId;
  console.log(infoEditForm.value,'infoEditForm.value')
};
const infoEditSubmit = async () => {
  console.log(infoEditForm.value,'infoEditForm.value11')
  infoEditFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      subLoading.value = true;
      let params = infoEditForm.value;
      const res = await api.selUpUwInfoEditSubmit(params);
      console.log(res, 'res');
      if (res.code !== 200) {
        subLoading.value = false;
        ElMessage.error(res.msg || '修改失败，请稍后再试！');
        return;
      }
      infoEditVisible.value = false;
      ElMessage.success('修改成功！');
      subLoading.value = false;
      // 刷新数据
      getInfoData();
      // emit('getList',{});
    }
  });
};
/** 查询企业信息 */
const getInfoData = async () => {
  const res = await api.customerImporDetail(memberId.value);
  form.value = res.data;
  workId.value = res.data.id || '';
  const resList = await api.selWkBankList(workId.value);
  console.log('查询银行卡信息:', resList);
  bankList.value = resList.rows || [];
  console.log('银行卡列表:', bankList.value);
};
 const settleChannelList = ref<any[]>([]);
// 获取结算通道
const getSettleChannel = async () => {
  try {
    const res = await api.getSettleChannel();
    console.log('获取结算通道:', res);
    if (res.code === 200) {
      settleChannelList.value = res.data;
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    console.error('获取结算通道失败:', error);
  }
};

// 返回
const returnOn = () => {
  proxy?.$router.go(-1);
  proxy?.$tab.closePage(route);
};
// 处理上传
const handleUpload = () => {
  // TODO: 实现文件上传逻辑
  proxy?.$modal.msgInfo('请实现文件上传功能');
};

// 编辑按钮点击事件
const handleEdit = (row: any) => {
  // 设置编辑表单的初始值
  console.log('编辑行数据:', row);
  editForm.value = {
    id: row.id,
    bankType: row.bankType,
    bankCard: row.bankCard,
    phone: row.phoneNoHide,
    workId: row.workId,
    passage: row.passage || '' // 添加结算通道字段
  };
  dialogVisible.value = true;
};

// 在顶层定义 editFormRef
const editFormRef = ref();

// 自雇者银行修改提交
const submitForm = async () => {
  await editFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await api.workerAccountEditSubmit({
          ...editForm.value,
        });
        if (res.code !== 200) {
          proxy?.$modal.msgError(res.msg);
          return;
        }
        proxy?.$modal.msgSuccess('修改成功');
        dialogVisible.value = false;
        getInfoData(); // 刷新数据
      } catch (error) {
        console.error('更新失败:', error);
      }
    }
  });
};

onMounted(() => {
  if (route.query.id) {
    memberId.value = route.query.id;
    // workId.value = route.query.workId;
    getInfoData(); // 查询企业信息
    getSettleChannel();
  }
});
</script>

<style lang="scss" scoped>
.card-header {
  font-weight: 700;
}
.mt40 {
  margin-top: 40px;
}
.el-divider--horizontal {
  margin: 15px 0;
}
.card-footer {
  margin-top: 20px;
  text-align: center;
}
</style>
